﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Marmat.FrameWork
{
    internal class DefaultHostBuilder : IHostBuilder
    {
        internal object Startup { get; set; }

        IHost IHostBuilder.Build()
        {
            ServiceCollectionFactory.SetServiceCollection(new Microsoft.Extensions.DependencyInjection.ServiceCollection());
            IServiceCollection serviceCollection = ServiceCollectionFactory.GetServiceCollection();
            if (this.Startup is IStartup startup)
                startup.ConfigureServices(serviceCollection);
            else
            {
                Type type = this.Startup.GetType();
                MethodInfo method = type.GetTypeInfo().GetMethod(nameof(IStartup.ConfigureServices), new Type[] { typeof(IServiceCollection) });
                if (method != null)
                    method.Invoke(this.Startup, new object[] { serviceCollection });
                else
                    throw new NotImplementedException($"{nameof(Startup)} 未实现 {nameof(IStartup.ConfigureServices)} 方法。");
            }

            IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
            ServiceCollectionFactory.SetServiceProvider(serviceProvider);
            return new DefaultWinHost();
        }
    }
}
